<?php
cmspad_import('Portlet');
interface IDispatcher{
	
	/**
	 * @param string $pathinfo
	 * @return string
	 */
	public function dispatch($pathinfo);

	/**
	 * @param string $portlet
	 * @param string $mehtod
	 * @param array $params
	 * @return string
	 */
	public function hyperlink($portlet = null, $mehtod = null, $params = null);
}

class Dispatcher{
	
	/**
	 * List the available URL routers.
	 *
	 * @return array
	 */
	public static function dispatchers(){
		cmspad_import('cache.DirectoryCache');
		$cache = new DirectoryCache('cmspad_dispatchers',dirname(__FILE__) . '/dispatcher/',DirectoryCache::$MODE_FILE,false);
		$files = array();
		foreach(array_keys($cache->value()) as $f){
			$l = strlen($f) > 5?strlen($f) - 4:0;
			if($l > 0 && substr($f,$l) == '.php'){
				$files[] = substr($f,0,$l);
			}
		}
		return $files;
	}
	
	/**
	 * @var IDispatcher
	 */
	private $router;
	
	public function __construct($router = '',$portal = ''){
		global $_CONFIG;
		
		// Init configuration
		if(!$router){
			if(isset($_CONFIG['DISPATCH']['ROUTER'])){
				$router = $_CONFIG['DISPATCH']['ROUTER'];
			}else{
				$router = 'default';
			}
		}
		if(!$portal){
			if(isset($_CONFIG['DISPATCH']['PORTAL'])){
				$portal = $_CONFIG['DISPATCH']['PORTAL'];
			}else{
				$portal = 'Portal';
			}
		}
		
		// Create router
		$routerDir = dirname(__FILE__) . '/dispatcher/';
		if(is_string($router)){
			$routerFile = $routerDir . $router . '.php';
			if(file_exists($routerFile)){
				include_once $routerFile;
				$routerClass = cmspad_get_class_name('cmspad_dispatcher_' . $router);
				if($routerClass){
					$this->router = new $routerClass($portal);
					$GLOBALS['_CMSPAD_DISPATCHER'] = $this->router;
				}else{
					header('HTTP/1.1 500 Internal Error');
					exit('URL Router Object Not Found: ' . $router);
				}
			}else{
				header('HTTP/1.1 500 Internal Error');
				exit('URL Router File Not Found: ' . $router);
			}
		}else if(is_a($router,'IDispatcher')){
			$this->router = $router;
		}else{
			header('HTTP/1.1 500 Internal Error');
			exit('Unknown URL Router Type: ' . print_r($router,true));
		}
	}
	
	public function dispatch($pathinfo){
		$pi = $this->router->dispatch($pathinfo);
		if(is_string($pi)){
			// Error Message
			header('HTTP/1.1 500 Internal Error');
			echo cmspad_template('error', array('message' => $pi));
		}else if(is_bool($pi)){
			if(!$pi){
				header('HTTP/1.1 404 Not Found');
				echo cmspad_template('error', array('title' => 'The Request URL Not Found：404', 'message' => '在该服务器上的请求URL不存在。 如果您是手动输入的URL地址，请重新检查一遍是否正确。 <br/>如果您认为这是一个服务器错误，请联系管理员。 <br/> 请求URL地址为：'.$pathinfo));
			}
		}
	}
}
?>